package com.tansun.easycare.rule.rulegroup.service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.tansun.easycare.rule.common.BomCreator;
import com.tansun.easycare.rule.common.FuncParse;
import com.tansun.easycare.rule.common.ParamParse;
import com.tansun.easycare.rule.common.RuleParseList;
import com.tansun.easycare.rule.common.jfun.JFun;
import com.tansun.easycare.rule.common.jfun.JFunCreator;
import com.tansun.easycare.rule.common.model.BaseBean;
import com.tansun.easycare.rule.common.model.Bom;
import com.tansun.easycare.rule.common.model.BomField;
import com.tansun.easycare.rule.common.model.Domain;
import com.tansun.easycare.rule.common.model.DomainItem;
import com.tansun.easycare.rule.common.model.ListTail;
import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.BlankFact;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.GroupFact;
import com.tansun.easycare.rule.common.rulebasebean.LineLogic;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.easycare.rule.common.symbol.DrlValue;
import com.tansun.easycare.rule.common.symbol.Symbol;
import com.tansun.easycare.rule.common.symbol.SymbolCreator;
import com.tansun.easycare.rule.common.symbol.SymbolGuide;
import com.tansun.easycare.rule.common.symbol.WidgetCreator;
import com.tansun.easycare.rule.datamodel.entity.RuleDataparams;
import com.tansun.easycare.rule.rulegroup.entity.RuleEntry;
import com.tansun.easycare.rule.rulegroup.entity.RuleGroup;
import com.tansun.easycare.rule.rulegroup.model.RuleEntryCondition;
import com.tansun.easycare.rule.rulegroup.model.RuleEntryVO;
import com.tansun.easycare.rule.rulegroup.model.RuleGroupVO;
import com.tansun.easycare.rule.rulegroup.model.RuleSetVO;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.utils.DroolsUtils;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.model.toolbean.RuleModel.RuleType;
import com.tansun.rule.utils.LoggerManager;

public class RuleParseDrl {
	/**
	 * 表示for、if、变量定义等语句
	 */
	private final String BLOCK_MARK = "@block@";
	/**
	 * 需要置顶的语句，如变量定义；
	 * 嵌套语句中，例如在多层for循环中无法定义临时变量，需要提前定义。
	 */
	private final String TOP_MARK = "@top@";
    private Map<String, Bom> indexBom;
    private Map<String, Bom> handlerBom;
    private Map<String, Domain> drlDomain;
    private Map<String, DrlValue> drlValueMap = WidgetCreator.getDrlValueMap();
    private static Map<String, ListTail> listTailMap = BomCreator.getListTailMap();
    private List<JFun> jfunList;
    private Map<String,String> funcParamMap;
    private Map<String,RuleDataparams> currentfuncParamMap= new HashMap<String,RuleDataparams>();
	public Map<String, String> getFuncParamMap() {
		return funcParamMap;
	}

	public void setFuncParamMap(Map<String, String> funcParamMap) {
		this.funcParamMap = funcParamMap;
	}

	/**
     * 构造fun
     *
     * @param path 规则项目路径
     */
    public RuleParseDrl(Map<String, Bom> indexBom, Map<String, Bom> handlerBom, Map<String, Domain> drlDomain, List<JFun> jfunList) {
        this.indexBom = indexBom;
        this.handlerBom = handlerBom;
        this.drlDomain = drlDomain;
        this.jfunList = jfunList;
    }

    /**
     * 生成规则集drl文本
     *
     * @return drl
     */
    public String xml2RuleItem(RuleSetVO ruleSetVo) throws Exception {
        try {
            RuleCollection rc = new RuleCollection();
            //rc.setComment(ruleSetVo.getComment());
            RuleModelTypeEnum modelTypeEnum = RuleModelTypeEnum.getRuleModelTypeEnum(ruleSetVo.getRuleManage().getModelType());
            rc.setContentType(modelTypeEnum.desc);
            rc.setDrlName(ruleSetVo.getRuleManage().getCode());
            rc.setVersion(ruleSetVo.getRuleManage().getVersion());
            rc.setObjName(ruleSetVo.getRuleManage().getName());
            Collections.sort(ruleSetVo.getRules());
            List<RuleGroup> list = ruleSetVo.getRules();
            for (RuleGroup ruleVo : list) {
                RuleItem ruleItem = transformVo2Item(ruleVo,false);
            	List<String> logsArr = new ArrayList<String>();//日志参数收集
                logsArr.add("droolsRuleLog.addLogs(\""+ruleSetVo.getRuleManage().getCode()+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");");
                logsArr.add("droolsRuleLog.addTracks(\""+ruleVo.getRuleName()+"\");");
                ruleItem.getdThen().setLogsArr(logsArr);
                rc.getListItem().add(ruleItem);
            }
            return DroolsUtils.convert2DrlTxt(rc);
        } catch (ParseException e) {
            LoggerManager.error("", e, this.getClass());
            return null;
        }

    }
    
    /**
     * 生成规则集drl文本,函数模式
     *
     * @return drl
     */
    public String xml2RuleItemFunc(RuleGroupVO ruleGroupVO) throws Exception {
    	try {
        	Set<String> initList =new HashSet<String>();
            RuleCollection rc = xml2RuleCollection(ruleGroupVO,initList,true);
            return DroolsUtils.convert2DrlFunc(rc,initList,RuleCollection.POLIRULEGRP,null);
        } catch (ParseException e) {
            LoggerManager.error("", e, this.getClass());
            return null;
        }
    }
    
    public RuleCollection xml2RuleCollection(RuleGroupVO ruleGroupVO,Set<String> initList,boolean changeType) throws Exception {
    	RuleManage ruleManage = ruleGroupVO.getRuleManage();
    	String code = ruleManage.getCode();
        RuleCollection rc = new RuleCollection();
        rc.setContentType(RuleType.policyrulegroup.toString());
        rc.setDrlName(ruleManage.getCode());
        rc.setVersion(ruleManage.getVersion());
        rc.setObjName(ruleManage.getName());

    	initList.add("ruleHelper.setValue($insertMap,\""+code+".ruleScoreSum\",0.0);");
        //普通条目
        List<RuleEntryVO> generalEntrys = ruleGroupVO.getGeneralEntrys();
        organGeneralEntrys(rc, generalEntrys, ruleManage, initList,changeType);
        
        //互斥条目
        List<RuleEntryVO> mutualExclusions = ruleGroupVO.getMutualExclusions();
        organMutualExclusions(rc, mutualExclusions, ruleManage, initList,changeType);
        
        RuleItem ruleItem = new RuleItem();
        ruleItem.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
        ruleItem.setSalience(-999999);
        ruleItem.setAddlog(0);
        List<Action> actionList = ruleItem.getdThen().getListAction();
        String activegroupList = "ruleHelper.insertValue($insertMap,\"builtinParam.activegroupList\",\""+ruleManage.getName()+"\");";
        actionList.add(new Action(activegroupList));
        String setList = "ruleHelper.dRemoval($insertMap,\""+code+".activeList\");";
        actionList.add(new Action(setList));
        setList = "ruleHelper.dRemoval($insertMap,\""+code+".reasonList\");";
        actionList.add(new Action(setList));
        rc.getListItem().add(ruleItem);
		return rc;
    }
    /**
     * 生成规则集drl文本
     *
     * @return drl
     */
    public String xml2RuleItem(RuleGroupVO ruleGroupVO) throws Exception {
        try {
        	Set<String> initList =new HashSet<String>();
            RuleCollection rc = xml2RuleCollection(ruleGroupVO,initList,false);
            return DroolsUtils.convert2DrlTxt(rc,initList);
        } catch (ParseException e) {
            LoggerManager.error("", e, this.getClass());
            return null;
        }

    }
    
    /**
     * 组织互斥条目的drl，互斥条目需要判断 
     * @param rc
     * @param generalEntrys
     * @param ruleManage
     * @throws Exception
     */
    public void organMutualExclusions(RuleCollection rc, List<RuleEntryVO> mutualExclusions, RuleManage ruleManage,Set<String> initList,boolean changeType) throws Exception {
    	String code = ruleManage.getCode();
    	List<String> entryNames = new ArrayList<String>();
        for(RuleEntryVO ruleEntryVO:mutualExclusions) {
        	RuleEntry ruleEntry = ruleEntryVO.getRuleEntry();
        	String entryCode = ruleEntry.getEntryCode();
        	String entryName = ruleEntry.getEntryName();
        	String accessMode = ruleEntry.getAccessMode();
        	List<RuleGroup> list = ruleEntryVO.getRules();
    		List<Fact> evalList = getEntryCondition(ruleEntryVO,ruleManage,changeType);

    		//判断条目名是否包含在列表中
			GroupFact groupfact = new GroupFact();
			groupfact.setContent("ruleHelper.valueNotInList($insertMap, \""+code+".activeEntryList\",\""+StringUtils.join(entryNames,"\",\"")+"\")");
    		
    		List<String> reasoncode = new ArrayList<String>();
    		List<String> tracks = new ArrayList<String>();
    		RuleItem ruleItem = null;
            for (RuleGroup ruleVo : list) {
            	List<String> logsArr = new ArrayList<String>();//日志参数收集
                logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\",\""+ruleVo.getRuleName()+"\",\""+ruleVo.getRuleScore()+"\",\""+ruleVo.getReasonCode()+"\");");
                logsArr.add("droolsRuleLog.addTracks(\""+entryName+"_"+ruleVo.getRuleName()+"\");");
                tracks.add(entryName+"]["+ruleVo.getRuleName());
                ruleItem = transformVo2Item(ruleVo,changeType);
                ruleItem.setRuleName(entryCode+"_"+ruleItem.getRuleName());
                ruleItem.getdThen().setLogsArr(logsArr);
                
                List<Fact> evals = ruleItem.getdWhen().getEvalList();//条件
                List<Action> actionList = ruleItem.getdThen().getListAction();//动作
                
                String reasonList = "ruleHelper.insertValue($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\");";
                actionList.add(new Action(reasonList));
                String ruleScoreSum = "ruleHelper.deAccumulating($insertMap,\""+code+".ruleScoreSum\",\""+code+".activeList\",\""+ruleVo.getRuleName()+"\","+ruleVo.getRuleScore()+");";
                actionList.add(new Action(ruleScoreSum));
                String activeList = "ruleHelper.insertValue($insertMap,\""+code+".activeList\",\""+ruleVo.getRuleName()+"\");";
                actionList.add(new Action(activeList));
                
                if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//优先级准入
                	//优先级判断条件
                	for(int i=0;i<evalList.size();i++) {
                    	Fact fact = evalList.get(i);
                    	evals.add(i, fact);
                    }
                	String priorityVar = (changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\")";
                	GroupFact gf = new GroupFact();
                	gf.setContent(priorityVar+" == "+ruleVo.getPriority()+" || "+priorityVar+" == 99999");
                	evals.add(0,gf);
                	
            		//优先级动作
            		String priorityCode = "ruleHelper.setValueNotMatch($insertMap, \""+code+"."+entryCode+"_priority\","+ruleVo.getPriority()+");";
	                actionList.add(new Action(priorityCode));
                }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
                	//添加条件准入条件，插入首位置
                	for(int i=0;i<evalList.size();i++) {
                    	Fact fact = evalList.get(i);
                    	evals.add(i, fact);
                    }
                }else if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
                	reasoncode.add(ruleVo.getReasonCode());
                	//权重累加动作
                    String totalweight = "ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\","+ruleVo.getRuleweight()+"+"+(changeType?"(Double)":"")+"ruleHelper.getValue($insertMap,\""+code+"."+entryCode+"_totalweight\"));";
                    actionList.add(new Action(totalweight));
                }
            	//添加判断，判断条目名是否包含在列表中
        		if(entryNames.size()>0) {
        			evals.add(0, groupfact);
            	}
                rc.getListItem().add(ruleItem);
            }
            
        	List<String> logsArr = new ArrayList<String>();//日志参数收集
            logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\");");
            logsArr.add("droolsRuleLog.addTracks(\""+entryName+"\");");
            
            RuleItem ruleItemOther = new RuleItem();
            ruleItemOther.setAddlog(0);
        	ruleItemOther.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid()+entryName);
        	if(ruleItem!=null) {
        		ruleItemOther.setSalience(ruleItem.getSalience());
        	}else {
        		ruleItemOther.setSalience(0);
        	}
            if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
            	//权重初始化
            	initList.add("ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\",0.0);");
            	
            	if(evalList.size()>0) {//没有命中
	            	GroupFact fact = new GroupFact();
	            	fact.setContent("!( "+evalList.get(0).getContent()+" )");
	            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	}
            	String removeReasonList = "ruleHelper.removeListValue($insertMap,\""+code+".reasonList\",\""+StringUtils.join(reasoncode,"\",\"")+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(removeReasonList));
            	String removeTrack = "droolsRuleLog.removeTracks(\""+StringUtils.join(tracks,"\",\"")+"\");";//删除命中轨迹
            	ruleItemOther.getdThen().getListAction().add(new Action(removeTrack));
            	
            	//判断是否添加条目
            	RuleItem ruleItemOther2 = new RuleItem();
            	ruleItemOther2.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            	ruleItemOther2.setSalience(ruleItemOther.getSalience());
            	ruleItemOther2.getdWhen().setEvalList(evalList); 
            	ruleItemOther2.getdThen().setLogsArr(ruleItemOther.getdThen().getLogsArr());
            	if(entryNames.size()>0) {
        			ruleItemOther2.getdWhen().getEvalList().add(0, groupfact);
            	}
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther2.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther2.getdThen().setLogsArr(logsArr);
            	ruleItemOther2.setAddlog(0);
            	rc.getListItem().add(ruleItemOther2);
            }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
            	ruleItemOther.getdWhen().setEvalList(evalList);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }else if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {
            	//优先级初始化
            	initList.add("ruleHelper.setValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\",99999);");
            	
            	GroupFact fact = new GroupFact();
            	fact.setContent((changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }
        	//添加判断，判断条目名是否包含在列表中
    		if(entryNames.size()>0) {
    			ruleItemOther.getdWhen().getEvalList().add(0, groupfact);
        	}
            rc.getListItem().add(ruleItemOther);
            entryNames.add(entryName);
        }
    }
    /**
     * 组织普通条目的drl
     * @param rc
     * @param generalEntrys
     * @param ruleManage
     * @throws Exception
     */
    public void organGeneralEntrys(RuleCollection rc, List<RuleEntryVO> generalEntrys, RuleManage ruleManage,Set<String> initList,boolean changeType) throws Exception {
    	String code = ruleManage.getCode();
        for(RuleEntryVO ruleEntryVO:generalEntrys) {
        	RuleEntry ruleEntry = ruleEntryVO.getRuleEntry();
        	String entryCode = ruleEntry.getEntryCode();
        	String entryName = ruleEntry.getEntryName();
        	String accessMode = ruleEntry.getAccessMode();
        	List<RuleGroup> list = ruleEntryVO.getRules();
    		List<Fact> evalList = getEntryCondition(ruleEntryVO,ruleManage,changeType);
    		List<String> reasoncode = new ArrayList<String>();
    		List<String> tracks = new ArrayList<String>();
    		RuleItem ruleItem = null;
            for (RuleGroup ruleVo : list) {
            	List<String> logsArr = new ArrayList<String>();//日志参数收集
                logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\",\""+ruleVo.getRuleName()+"\",\""+ruleVo.getRuleScore()+"\",\""+ruleVo.getReasonCode()+"\");");
                logsArr.add("droolsRuleLog.addTracks(\""+entryName+"]["+ruleVo.getRuleName()+"\");");
                tracks.add(entryName+"]["+ruleVo.getRuleName());
                
                ruleItem = transformVo2Item(ruleVo,changeType);
                ruleItem.setRuleName(entryCode+"_"+ruleItem.getRuleName());
                ruleItem.getdThen().setLogsArr(logsArr);
                
                List<Fact> evals = ruleItem.getdWhen().getEvalList();//条件
                List<Action> actionList = ruleItem.getdThen().getListAction();//动作
                
                String reasonList = "ruleHelper.insertValue($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\");";
                actionList.add(new Action(reasonList));
                String ruleScoreSum = "ruleHelper.deAccumulating($insertMap,\""+code+".ruleScoreSum\",\""+code+".activeList\",\""+ruleVo.getRuleName()+"\","+ruleVo.getRuleScore()+");";
                actionList.add(new Action(ruleScoreSum));
                String activeList = "ruleHelper.insertValue($insertMap,\""+code+".activeList\",\""+ruleVo.getRuleName()+"\");";
                actionList.add(new Action(activeList));
                
                if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//优先级准入
                	//优先级判断条件
                	for(int i=0;i<evalList.size();i++) {
                    	Fact fact = evalList.get(i);
                    	evals.add(i, fact);
                    }
                	String priorityVar = (changeType?"(Long)":"")+"ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\")";
                	GroupFact gf = new GroupFact();
                	gf.setContent(priorityVar+" == "+ruleVo.getPriority()+" || "+priorityVar+" == 99999");
                	evals.add(0,gf);
            		
            		//优先级动作
            		String priorityCode = "ruleHelper.setValueNotMatch($insertMap, \""+code+"."+entryCode+"_priority\","+ruleVo.getPriority()+");";
	                actionList.add(new Action(priorityCode));
                }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
                	//添加条件准入条件，插入首位置
                	for(int i=0;i<evalList.size();i++) {
                    	Fact fact = evalList.get(i);
                    	evals.add(i, fact);
                    }
                }else if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
                	reasoncode.add(ruleVo.getReasonCode());
                	
                	//权重累加动作
                    String totalweight = "ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\","+ruleVo.getRuleweight()+"+"+(changeType?"(Double)":"")+"ruleHelper.getValue($insertMap,\""+code+"."+entryCode+"_totalweight\"));";
                    actionList.add(new Action(totalweight));
                }
                rc.getListItem().add(ruleItem);
            }
            
        	List<String> logsArr = new ArrayList<String>();//日志参数收集
            logsArr.add("droolsRuleLog.addLogs(\""+code+"\",\"" + rc.getContentType() + "\",\"" + rc.getObjName() + "\", drools, \""+entryName+"\");");
            logsArr.add("droolsRuleLog.addTracks(\""+entryName+"\");");
            
            RuleItem ruleItemOther = new RuleItem();
            ruleItemOther.setAddlog(0);
        	ruleItemOther.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
        	if(ruleItem!=null) {
        		ruleItemOther.setSalience(ruleItem.getSalience());
        	}else {
        		ruleItemOther.setSalience(0);
        	}
            if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)) {//权重准入
            	//权重初始化
            	initList.add("ruleHelper.setValue($insertMap,\""+code+"."+entryCode+"_totalweight\",0.0);");
            	
            	if(evalList.size()>0) {//权重不符条件，删除原因代码
	            	GroupFact fact = new GroupFact();
	            	fact.setContent("!( "+evalList.get(0).getContent()+" )");
	            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	}
            	String removeReasonList = "ruleHelper.removeListValue($insertMap,\""+code+".reasonList\",\""+StringUtils.join(reasoncode,"\",\"")+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(removeReasonList));
            	String removeTrack = "droolsRuleLog.removeTracks(\""+StringUtils.join(tracks,"\",\"")+"\");";//删除命中轨迹
            	ruleItemOther.getdThen().getListAction().add(new Action(removeTrack));
            	
            	//判断是否添加条目，符合条件，添加
            	RuleItem ruleItemOther2 = new RuleItem();
            	ruleItemOther2.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            	ruleItemOther2.setSalience(ruleItemOther.getSalience());
            	ruleItemOther2.getdWhen().setEvalList(evalList);
            	
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther2.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther2.getdThen().setLogsArr(logsArr);
            	ruleItemOther2.setAddlog(0);
            	rc.getListItem().add(ruleItemOther2);
            }else if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//
            	ruleItemOther.getdWhen().setEvalList(evalList);//规则命中
            	
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }else if(RuleEntry.ACCESSMODEL_PRIORITY_2.equals(accessMode)) {//规则命中
            	//优先级初始化
            	initList.add("ruleHelper.setValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\",99999);");
            	
            	GroupFact fact = new GroupFact();
            	if(changeType) {
            		fact.setContent("(Long)ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	}else {
            		fact.setContent("ruleHelper.getValueNotMatch($insertMap,\""+code+"."+entryCode+"_priority\") != 99999");
            	}
            	ruleItemOther.getdWhen().getEvalList().add(fact);
            	String activeEntryList = "ruleHelper.insertValue($insertMap,\""+code+".activeEntryList\",\""+entryName+"\");";
            	ruleItemOther.getdThen().getListAction().add(new Action(activeEntryList));
            	ruleItemOther.getdThen().setLogsArr(logsArr);
            }
            rc.getListItem().add(ruleItemOther);
        }
    }
    /**
     * 将规则条目解析对应的条件
     * @param ruleEntryVO
     * @return
     */
    public List<Fact> getEntryCondition(RuleEntryVO ruleEntryVO, RuleManage ruleManage,boolean changType) {
    	List<Fact> facts = new ArrayList<Fact>();//条件结果
    	RuleEntry ruleEntry = ruleEntryVO.getRuleEntry();
    	String accessMode = ruleEntry.getAccessMode();
    	if(RuleEntry.ACCESSMODEL_COND_0.equals(accessMode)) {//条件准入
    		String condition = ruleEntry.getConditions();
    		if(StringUtils.isNotEmpty(condition)) {
    			facts = transform2Facts(condition,changType);
    		}
    	}else if(RuleEntry.ACCESSMODEL_WEIGHT_1.equals(accessMode)){//权重准入
    		List<RuleEntryCondition> conditions = ruleEntryVO.getConditions();
    		if(conditions!=null) {
        		String var = (changType?"(Double)":"")+"ruleHelper.getValue($insertMap,\""+ruleManage.getCode()+"."+ruleEntry.getEntryCode()+"_totalweight\")";
        		String content = "";
        		for(RuleEntryCondition cond:conditions) {
        			String optSym = cond.getOptSym();
        			String symbol = cond.getSymbol();
        			String symbolVal = cond.getSymbolVal();
        			if(StringUtils.isNotEmpty(optSym)) {
        				content += " "+optSym+ " " + var + " " + symbol + " " + symbolVal;
        			}else {
        				content +=  var + " " + symbol + " " + symbolVal;
        			}
        		}
        		GroupFact groupfact = new GroupFact();
        		groupfact.setContent(content);
        		facts.add(groupfact);
        	}
    	}
    	for(Fact fact:facts) {
    		fact.setType(Fact.TYPE_ENTRY);
    	}
		return facts;
    	
    }
    /**
     * 生成规则集drl文本,没有权重
     *
     * @return drl
     */
    public String xml2RuleItemNoWeight(RuleSetVO ruleSetVo) throws Exception {
        try {
        	String code = ruleSetVo.getRuleManage().getCode();
            RuleCollection rc = new RuleCollection();
            rc.setContentType(RuleType.policyrulegroup.toString());
            rc.setDrlName(code);
            rc.setVersion(ruleSetVo.getRuleManage().getVersion());
            rc.setObjName(ruleSetVo.getRuleManage().getName());
            Collections.sort(ruleSetVo.getRules());
            List<RuleGroup> list = ruleSetVo.getRules();
            for (RuleGroup ruleVo : list) {
                RuleItem ruleItem = transformVo2Item(ruleVo,false);
                List<Action> actionList = ruleItem.getdThen().getListAction();//动作
                
                String reasonList = "ruleHelper.setValueType($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\",\"String\");";
                actionList.add(new Action(reasonList));
                String ruleScoreSum = "ruleHelper.setValueType($insertMap,\""+code+".ruleScoreSum\","+ruleVo.getRuleScore()+",\"Double\");";
                actionList.add(new Action(ruleScoreSum));
                rc.getListItem().add(ruleItem);
            }
            RuleItem ruleItem = new RuleItem();
            ruleItem.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            ruleItem.setSalience(-9999);
            rc.getListItem().add(ruleItem);
            return DroolsUtils.convert2DrlTxt(rc);
        } catch (ParseException e) {
            LoggerManager.error("", e, this.getClass());
            return null;
        }

    }
    
    /**
     * 生成规则drl文本,函数模式
     *
     * @return drl
     */
    public String xml2RuleItemForJava(RuleSetVO ruleSetVo) throws Exception {
    	try {
    		String code = ruleSetVo.getRuleManage().getCode();
    		String modelType = ruleSetVo.getRuleManage().getModelType();
            RuleCollection rc = new RuleCollection();
            rc.setContentType(RuleType.policyrulegroup.toString());
            rc.setDrlName(code);
            rc.setVersion(ruleSetVo.getRuleManage().getVersion());
            rc.setObjName(ruleSetVo.getRuleManage().getName());
            Collections.sort(ruleSetVo.getRules());
            List<RuleGroup> list = ruleSetVo.getRules();
            for (RuleGroup ruleVo : list) {
                RuleItem ruleItem = transformVo2Item(ruleVo,true);
                List<Action> actionList = ruleItem.getdThen().getListAction();//动作
                
                String reasonList = "ruleHelper.setValueType($insertMap,\""+code+".reasonList\",\""+ruleVo.getReasonCode()+"\",\"String\");";
                actionList.add(new Action(reasonList));
                String ruleScoreSum = "ruleHelper.setValueType($insertMap,\""+code+".ruleScoreSum\","+ruleVo.getRuleScore()+",\"Double\");";
                actionList.add(new Action(ruleScoreSum));
                rc.getListItem().add(ruleItem);
            }
            RuleItem ruleItem = new RuleItem();
            ruleItem.setRuleName(com.tansun.rule.utils.StringUtils.generateShortUuid());
            ruleItem.setSalience(-9999);
            rc.getListItem().add(ruleItem);
            Set<String> initList =new HashSet<String>();
            if( RuleModelTypeEnum.SimpleRuleGroup.code.equals(modelType) ) {
            	return DroolsUtils.convert2DrlFunc(rc,initList,RuleCollection.SIMPLERULEGRP,null);
            }else {
            	return DroolsUtils.convert2DrlFunc(rc,initList,RuleCollection.POLIRULEGRP,null);
            }
        } catch (ParseException e) {
            LoggerManager.error("", e, this.getClass());
            return null;
        }
    }
    /**
     * 开启类型转换
     * @param conditionHtml
     * @param typeChange
     * @return
     */
    public List<Fact> transform2Facts(String conditionHtml,boolean typeChange) {
        List<String> evalDivs = new ArrayList<String>();
        getListDivStr(evalDivs, conditionHtml);
        List<Fact> evalList = new ArrayList<Fact>();
        try {
	        for (String spans : evalDivs) {
	            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
	            getListSpanMap(list, spans);
	            LineLogic lineLogic = getLineLogic(spans);
				evalHandler(list, evalList,lineLogic,typeChange);
	        }
		} catch (Exception e) {
			LoggerManager.error("节点条件解析错误", e, this.getClass());
			e.printStackTrace();
		}
        return evalList;
    }
    
    /**
     * 把xml对应的描述对象转为drl对应的规则对象
     * @param ruleVo 规则集
     * @param typeChange true=使用java模式 false=使用drl模式
     */
    public RuleItem transformVo2Item(RuleGroup ruleVo,boolean typeChange) throws Exception {
        RuleItem ruleItem = new RuleItem();
        ruleItem.setActivationGroup(ruleVo.getActivationGroup());
        ruleItem.setComment(ruleVo.getComment());
        ruleItem.setDateEffective(ruleVo.getDateEffective());
        ruleItem.setDateExpires(ruleVo.getDateExpires());
        ruleItem.setEnabled(ruleVo.getEnabled());
        ruleItem.setRuleName(ruleVo.getRuleName());
        if (ruleVo.getSalience() != null)
            ruleItem.setSalience(ruleVo.getSalience());
        ruleItem.setTxtType(ruleVo.getTxtType());

        //设置fact
        List<String> factDivs = new ArrayList<String>();
        getListDivStr(factDivs, ruleVo.getFacts());
        for (String spans : factDivs) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            getListSpanMap(list, spans);
            factHandler(list, ruleItem.getdWhen().getFactList(),typeChange);
        }
        //设置eval
        List<String> evalDivs = new ArrayList<String>();
        getListDivStr(evalDivs, ruleVo.getEvals());
        for (String spans : evalDivs) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            LineLogic lineLogic = getLineLogic(spans);
            getListSpanMap(list, spans);
            evalHandler(list, ruleItem.getdWhen().getEvalList(),lineLogic,typeChange);
            //factHandler(list, ruleItem.getdWhen().getFactList());
        }
        //设置action
        List<String> actionDivs = new ArrayList<String>();
        getListDivStr(actionDivs, ruleVo.getActions());
        for (String spans : actionDivs) {
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            getListSpanMap(list, spans);
            actionHandler(list, ruleItem.getdThen().getListAction(),typeChange);
        }


        return ruleItem;
    }

    /**
     * 切分div
     */
    public void getListDivStr(List<String> divs, String pcontent) {
        if(StringUtils.isEmpty(pcontent)){
            return;
        }
        String content = pcontent.replaceAll("DIV>", "div>").replaceAll("<DIV", "<div").trim();

        int e = content.indexOf("</div>");
        if (e > 0) {
            String nextContent = content.substring(e + 6);
            divs.add(content.substring(0, e + 6));
            getListDivStr(divs, nextContent);
        }
    }

    /**
     * 转换span 为map
     */
    public void getListSpanMap(List<Map<String, String>> list, String pcontent) {

        //System.out.println("//-------------------------------------------------");
        String content = pcontent.replaceAll("<SPAN", "<span").replaceAll("SPAN>", "span>");
        Pattern pattern = Pattern.compile("<span([^>]*)>");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            String span = matcher.group();
            //String s1 = span.replaceFirst("class=\"[^ ]*\" ", "");
            //		System.out.println(s1);
            String s2 = span.replaceFirst("onclick=\"[^ ]*\"", "").replaceFirst("<span ", "").replace(">", "").trim().replaceAll("\\s{1,}", " ").replaceAll("\"", "").replaceAll("\'", "");
            //		System.out.println(s2);
            Map<String, String> map = new HashMap<String, String>();
            String[] ss = s2.split(" ");
            for (String s : ss) {
                if (s.indexOf("=") < 0) {
                    continue;
                }
                String name = s.substring(0, s.indexOf("=")).trim().toLowerCase();
                String value = s.substring(s.indexOf("=") + 1, s.length()).trim();
                map.put(name, value);


            }
            list.add(map);

        }
    }

    /**
     * 切片select
     * @param selects
     * @param pcontent
     */
    public void getListSelect(List<String> selects, String pcontent) {
    	String content = pcontent.replaceAll("<Select", "<select").replaceAll("Select>", "select>").replaceAll("<span(.*)</span>", "").trim();

        int e = content.indexOf("</select>");
        if (e > 0) {
            String nextContent = content.substring(e + 9);
            selects.add(content.substring(0, e + 9));
            getListSelect(selects, nextContent);
        }
    }
    /**
     * 解析每一行的逻辑关系
     * @param spans
     * @return
     */
    public LineLogic getLineLogic(String spans){
    	List<String> selects = new ArrayList<String>();
    	getListSelect(selects, spans);
    	LineLogic lineLogic = new LineLogic();
    	Pattern patternSel = Pattern.compile(".*<select([^>]*)name=\"([^>^=]*)\"([^>]*)>.*");
    	Pattern patternOpt = Pattern.compile(".*<option([^>]*)value=\"([^>^=]*)\"([^>]*)selopt=\"1\"([^>]*)>.*");
    	for(int i=0;i<selects.size();i++) {
    		String content = selects.get(i);
    		 Matcher matcher = patternSel.matcher(content);
    		 String name = null;
    		 if (matcher.find()) {
    			 name = matcher.group(2);
    		 }
    		 matcher = patternOpt.matcher(content);
    		 String optionVal = null;
    		 if (matcher.find()) {
    			 optionVal = matcher.group(2);
    		 }
			 if("leftbrackets".equals(name)) {
				 lineLogic.setLeft(optionVal);
			 }else if("linelogic".equals(name)) {
				 lineLogic.setLogic(optionVal);
			 }else if("rightbrackets".equals(name)) {
				 lineLogic.setRight(optionVal);
			 }
    	}
    	
		return lineLogic;
    }

    //fact部分转换
    private void factHandler(List<Map<String, String>> list, List<Fact> listFacts,boolean typeChange) throws Exception {
        Fact fact = new GroupFact();

        if (list.size() > 0 && "List".equals(list.get(0).get("grouptype"))) {
            fact = new BlankFact();
			String tempstr = null;
            if(typeChange) {
            	tempstr = spanMap2Java(list,true,"right",new ArrayList<String>());
            }else {
            	tempstr = spanMap2Drl(list,true,"right");
            }
            String itemDataType = list.get(0).get("datatype");
            String[] partstr = tempstr.split(";");
            String name = partstr[0].split(":")[0].trim();
            String bom = partstr[0].split("@~@")[1];
            String bompath = bom.replaceFirst("this", "").replaceAll("\"\\]\\[\"", ".").replaceAll("\\[\"", "").replaceAll("\"\\]", "").trim();


            String content = "";

            List<String> sizepart = new ArrayList<String>();
            List<String> thispart = new ArrayList<String>();

            for (int i = 1; i < partstr.length; i++) {
                String cond = partstr[i].replace("@~@", "");
                if (cond.indexOf("#size#") >= 0) {
                    cond = cond.replace("#size#", "size");
                    sizepart.add(cond);
                }
                if (cond.indexOf("#item#") >= 0) {
                    if ("Long".equals(itemDataType)) {
                        cond = cond.replace("#item#", "longValue");
                        thispart.add(cond);

                    } else if ("Double".equals(itemDataType)) {
                        cond = cond.replace("#item#", "doubleValue");
                        thispart.add(cond);

                    } else if ("String".equals(itemDataType) || "Boolean".equals(itemDataType) || "Date".equals(itemDataType)) {
                        cond = cond.replace("#item#", "this");
                        thispart.add(cond);

                    }
                }
                if (cond.matches(".*\\[\".*\"\\].*")) {
                    cond = cond.replace("[\"", "this[\"");
                    thispart.add(cond);
                }
            }

            //基础类型
            if (isBaseType(itemDataType)) {
                if (itemDataType.equalsIgnoreCase("long") || itemDataType.equalsIgnoreCase("double")) {
                    content = name + " : List(" + addSplitToString(sizepart, ", ") + ")from collect(Number(" + addSplitToString(thispart, ", ") + ") from (List)ruleHelper.getValue($insertMap,\"" + bompath + "\"))";

                } else if (itemDataType.equalsIgnoreCase("string")) {
                    content = name + " : List(" + addSplitToString(sizepart, ", ") + ")from collect(String(" + addSplitToString(thispart, ", ") + ") from (List)ruleHelper.getValue($insertMap,\"" + bompath + "\"))";

                } else if (itemDataType.equalsIgnoreCase("date")) {
                    content = name + " : List(" + addSplitToString(sizepart, ", ") + ")from collect(Date(" + addSplitToString(thispart, ", ") + ") from (List)ruleHelper.getValue($insertMap,\"" + bompath + "\"))";

                } else if (itemDataType.equalsIgnoreCase("boolean")) {
                    content = name + " : List(" + addSplitToString(sizepart, ", ") + ")from collect(Boolean(" + addSplitToString(thispart, ", ") + ") from (List)ruleHelper.getValue($insertMap,\"" + bompath + "\"))";

                }

                //对象类型
            } else {
                content = name + " : List(" + addSplitToString(sizepart, ", ") + ")from collect(Map(" + addSplitToString(thispart, ", ") + ") from (List)ruleHelper.getValue($insertMap,\"" + bompath + "\"))";

            }
            fact.setContent(content);
            //一般基础类型声明语句
        } else {
            if(typeChange) {
            	fact.setContent(spanMap2Java(list,false,"right",new ArrayList<String>()));
            }else {
            	fact.setContent(spanMap2Drl(list,false,"right"));
            }
			
        }


        listFacts.add(fact);
    }

    private String addSplitToString(List<String> list, String splitor) {
        String result = "";
        for (int i = 0; i < list.size(); i++) {
            if (i != 0) {
                result = result + splitor;
            }
            result = result + list.get(i);

        }
        return result;
    }

    //eval部分转换
    private void evalHandler(List<Map<String, String>> list, List<Fact> listEvals, LineLogic lineLogic,boolean typeChange) throws Exception {

        //Eval eval = new Eval();
        Fact eval = new GroupFact();
        if(typeChange) {
        	eval.setContent(spanMap2Java(list, false,"left",new ArrayList<String>()));
        }else {
        	eval.setContent(spanMap2Drl(list, false,"left"));
        }
		eval.setLineLogic(lineLogic);
        listEvals.add(eval);

    }

    //action部分转换
    private void actionHandler(List<Map<String, String>> list, List<Action> listAcations,boolean typeChange) throws Exception {
        Action action = new Action();
		String drlaction = null;
		typeChange = true;//使用java模式
		List<String> annotationList = new ArrayList<String>();
        if(typeChange) {
        	drlaction = spanMap2Java(list, false,"right",annotationList);
        }else {
        	drlaction = spanMap2Drl(list, false,"right");
        }
        String setStr = "";
        //赋值
        if (drlaction.indexOf("::=") >= 0) {
            String[] setValueStr = drlaction.split("::=");
            String left = setValueStr[0].replaceFirst("this", "").replaceAll("\"\\]\\[\"", ".").replaceAll("\\[\"", "").replaceAll("\"\\]", "").trim();
            //if()
            String right = setValueStr[1];
            String[] rightItem = right.split(" ");
            String rightResult = "";
            for (String string : rightItem) {
                if (string.matches("this\\[\".*\"\\]")) {
                    rightResult = rightResult + " " + transformActionBom(string, indexBom);
                } else {
                    rightResult = rightResult + " " + string;
                }
            }
            rightResult = rightResult.replaceAll("&quot;", "\\\\\"");//将html转义符还原回去
            if(setValueStr[0].startsWith("this[")){//数据模型中的对象赋值
            	setStr = "ruleHelper.setValue($insertMap, \"" + left + "\", " + rightResult + ");";
            }else{//临时对象赋值
            	setStr = setValueStr[0]+" = "+rightResult +";";
            }
            //action.setContent(setStr);
            //插入
        } else if (drlaction.indexOf("@@=") >= 0) {

            String[] setValueStr = drlaction.split("@@=");
            String left = setValueStr[0].replaceFirst("this", "").replaceAll("\"\\]\\[\"", ".").replaceAll("\\[\"", "").replaceAll("\"\\]", "").trim();
            //if()
            String right = setValueStr[1];

            //this["rating_info"]["mylist22"]@@={name:"null",type:"sss",bigValue:111}
            if (drlaction.matches(".*\\{.*\\}.*")) { //插入对象
                String jsonstr = "\"" + right.replaceAll("\"", "\\\\\"") + "\"";
                jsonstr = jsonstr.replace("drools.getRule().getAgendaGroup()", "\"+drools.getRule().getAgendaGroup()+\"");
                jsonstr = jsonstr.replace("drools.getRule().getName()", "\"+drools.getRule().getName()+\"");

                setStr = "ruleHelper.insertObject($insertMap, \"" + left + "\", " + jsonstr + ");";
            } else {//插入值
                setStr = "ruleHelper.insertValue($insertMap, \"" + left + "\", " + right + ");";

            }
        } else if(drlaction.startsWith(BLOCK_MARK)){
        	setStr = drlaction.split(BLOCK_MARK)[1];
        	//判断是否包含需要置顶的语句(例：for语句中的临时变量需要在外面事先定义)
        	if(setStr.contains(TOP_MARK)){
        		String top = setStr.split(TOP_MARK)[0];
        		if(listAcations.size()>0){
        			listAcations.get(0).setContent(top+listAcations.get(0).getContent());
        			setStr = setStr.split(TOP_MARK)[1];
        		}else{
        			setStr = setStr.replace(TOP_MARK, "");
        		}
        	}
        }else {
        	setStr = drlaction;
        }
        
        StringBuffer sb = new StringBuffer();
        for(String annotation:annotationList) {
        	sb.append(annotation);
        }
		if(!typeChange) {
		  	String reg = "this(\\[\"[a-zA-Z_0-9]*\"\\])+";
			Pattern pattern = Pattern.compile(reg);
			Matcher matcher = pattern.matcher(setStr);
			while (matcher.find()) {
			 	 	String result = matcher.group();
			  	String conter = transformActionBom(result, indexBom);
			  	setStr = setStr.replace(result, "("+conter+")");
			  	//matcher.appendReplacement(sb, conter);
			  	// System.out.println(result);
			}
			//matcher.appendTail(sb);
			//System.out.println(sb);
		}
		
		setStr = addSemicolon(setStr);//添加分号

        sb.append(setStr);
        action.setContent(sb.toString());
        listAcations.add(action);

    }

	private String spanMap2Drl(List<Map<String, String>> list, boolean achoroperflag,String leftOrRight) throws Exception{
        String drlrow = "";
		String dataType = "";
        Map<String,?> preMap = null;

        //函数处理标识
        String funName = null;
        //Map<String, String > funParas = null;
        String paramName = null;
        String temprow = null;
        String funStr = "";
        //String lanrgid = null;

        //数据组 in or notin处理标识
        boolean flagCollConetent = false;
        //for,if语句处理标识
        String block = null;
        String forIndex = null;//for语句索引变量
        String forEle = null;//循环子元素
        int index = 0;
        String paramInfo = "";
        for (Map<String, String> map : list) {
            String type = map.get("type");
            String id = map.get("id");
            String name = map.get("name");
            //如果是函数变量，进行特殊处理，获取函数变量关联的方法进行替换
            String currisfuncparam = map.get("isfuncparam");
            if(list.size()>index+1) {
            	Map<String, String> nextMap = list.get(index+1);
            	String nextisfuncparam = nextMap.get("isfuncparam");
            	index++;
            	if("1".equals(nextisfuncparam)) {
            		paramInfo = name;
            		continue;
            	}
            }

            if("1".equals(currisfuncparam)) {
            	RuleDataparams ruledp = new RuleDataparams();
            	ruledp.setClassName(paramInfo);
            	ruledp.setName(name);
            	String key = paramInfo+"."+name;
            	if(!currentfuncParamMap.containsKey(key))currentfuncParamMap.put(key, ruledp);
            	drlrow += funcParamMap.get(key);
        		continue;
        	}
            if (type == null || "".equals(type) || BaseBean.TYPE_OPER.equals(type)) {
                continue;
            }

            if (flagCollConetent) {
                drlrow = drlrow + ", ";
            }
            //函数开始
            if (BaseBean.TYPE_JFUN.equals(type) && "left".equals(map.get("side"))) {
            	
                JFun fun = JFunCreator.getJFunById(id);
//                if (fun == null) {
//                    fun = JFunCreator.getJFunById(id, this.getClass().getClassLoader().getResource("config/jfun.xml").getPath());
//                }
                if (fun == null) {
                    fun = findJFunById(id);
                }
                funName = fun.getDrlName();
                //funStr = fun.getDrlName()+"(";
                funStr = fun.getDrlName();
                String[] listpname = fun.sortParamName();
                for (int i = 0; i < listpname.length; i++) {
                    if (listpname[i] == null) {
                        break;
                    }
                    if (i == 0) {
                        funStr = funStr + "\\{" + listpname[i] + "\\}";
                    } else {
                        funStr = funStr + ", \\{" + listpname[i] + "\\}";
                    }
                }
//                funStr = funStr + ")";
                //funParas = new HashMap<String, String>();
                temprow = drlrow;    //drlrow 行增长字符串占时停用 切换为函数增长字符串
                drlrow = "";
                //函数结束
            } else if (BaseBean.TYPE_JFUN.equals(type) && "right".equals(map.get("side"))) {
                //JFun fun = JFunCreator.getJFunById(id);
                funName = null;
                paramName = null;
                funStr = funStr + ")";
                temprow = temprow + funStr;
                drlrow = temprow;
                //参数锚点
            } else if (BaseBean.TYPE_ANCHOR.equals(type) && "anchor_funparam".equals(map.get("class"))) {

                paramName = map.get("paramname");
                //一个参数结束
//            } else if (funName != null && paramName != null && BaseBean.TYPE_SYMBOL.equals(type) && "semi".equals(map.get("symtype"))) {
            } else if (funName != null && BaseBean.TYPE_SYMBOL.equals(type) && "semi".equals(map.get("symtype"))) {
				if(!org.apache.commons.lang3.StringUtils.isEmpty(dataType)){
					drlrow =  "("+dataType+")"+drlrow;
				}
				if(!StringUtils.isEmpty(paramName)) {
					 funStr = funStr.replace("\\{" + paramName + "\\}", drlrow);
					 paramName=null;
				}else {
					 funStr += ","+drlrow;
				}
                drlrow = "";
				dataType = "";
            } else if (BaseBean.TYPE_ANCHOR.equals(type) && ("for".equals(map.get("block"))||"if".equals(map.get("block"))||"return".equals(map.get("block")))) {
            	//for循环标记
                block = map.get("block");
                forIndex = map.get("forindex");
        		forEle = map.get("forele");
                
            } else if("end".equals(type)){
            	drlrow = BLOCK_MARK+"}";
            } else if("else".equals(type)){
            	drlrow = BLOCK_MARK+"}else{";
            }


            //站位显示
            //变量
            if (BaseBean.TYPE_TEMP.equals(type) || BaseBean.TYPE_SHOW.equals(type)) {
            	if("var".equals(map.get("block"))){
            		String var = map.get("value");
            		drlrow = BLOCK_MARK+var+" = null;\r\n"+TOP_MARK+var+"= new HashMap();";
            		return drlrow;
            	}
                drlrow = drlrow + map.get("value");
				dataType = map.get("datatype");
                //赋值符号
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && SymbolGuide.SYMTYP_LIST.equals(map.get("symtype"))) {
            	drlrow = drlrow + SymbolCreator.getSymbolById(id).getDrlSymbol();
                //锚点起始bom对象
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && SymbolGuide.SYMTYP_DECLARE.equals(map.get("symtype"))) {
                drlrow = drlrow + " : ";
                //锚点起始bom对象
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && !SymbolGuide.SYMTYP_SEMICOLON.equals(map.get("symtype"))) {
            		drlrow = drlrow + SymbolCreator.getSymbolById(id).getDrlSymbol();
                //list的添加
            } else if (BaseBean.TYPE_BOM.equals(type) && this.handlerBom.get(name) != null && BaseBean.TYPE_ANCHOR.equals(map.get("lefttype"))) {
            	if("for".equals(block)){
            		drlrow = name;
            	}else if(leftOrRight.equals("left")){
            		drlrow = drlrow+ "ruleHelper.getValue($insertMap,\""+name;
				}else{
					drlrow = drlrow + "this[\"" + name + "\"]";
				}
                //bom对象或属性
            } else if (BaseBean.TYPE_BOM.equals(type)) {
            	if("for".equals(block)){
            		if("list".equals(map.get("grouptype"))){
            			drlrow =BLOCK_MARK//语句块标识
            					+ "Map "+forEle+"=null;\r\n"
            					+ "int "+forIndex+"=0;\r\n"+TOP_MARK
            					+ String.format("for( %1$s=0;%1$s < ((List)ruleHelper.getValue($insertMap,\"%2$s\")).size();%1$s++){\r\n", forIndex,drlrow+"."+name)
            					+ String.format(" %1$s = (Map)((List)ruleHelper.getValue($insertMap,\"%2$s\")).get(%3$s);\r\n", forEle,drlrow+"."+name,forIndex);
            		}else if("Long".equals(map.get("datatype"))){
	            		drlrow =BLOCK_MARK//语句块标识
	            				+ "int "+forIndex+"=0;\r\n"+TOP_MARK
	            				+ String.format("for( %1$s=0;%1$s < ruleHelper.getValue($insertMap,\"%2$s\");%1$s++){\r\n", forIndex,drlrow+"."+name);
            			
            		}
            	}else if (preMap != null && BaseBean.TYPE_LISTTAIL.equals(preMap.get("type"))) {
                    drlrow = drlrow + ".get(\"" + name + "\")";
                } else {
					if(leftOrRight.equals("left")){
	            		drlrow = drlrow+ "."+name+"\")";
					}else{
                    drlrow = drlrow + "[\"" + name + "\"]";
                }
				}
                //括号
            } else if (BaseBean.TYPE_GROUP.equals(type)) {
                if ("rightgroup".equals(map.get("handtype").toLowerCase())) {
                    drlrow = drlrow + " ) ";
                } else {
                    drlrow = drlrow + " ( ";
                }
                if ("leftgroup".equals(map.get("handtype").toLowerCase()) && "coll".equals(map.get("widget"))) {
                    flagCollConetent = true;
                }
                if ("rightgroup".equals(map.get("handtype").toLowerCase()) && "coll".equals(map.get("widget"))) {
                    flagCollConetent = false;
                    //剔除多余的逗号
                    drlrow = drlrow.replaceAll("\\(\\s*,", "(").replaceAll(",\\s*,\\s*\\)", ")");
                }
                //list tail
            } else if (BaseBean.TYPE_LISTTAIL.equals(type)) {
                if ("size".equals(name)) {
                    drlrow = drlrow + ".size()";
                } else if ("item".equals(name)) {
                    drlrow = drlrow + ".get(" + map.get("index").trim() + ") ";
                }
                //值
            } else if (BaseBean.TYPE_VALUE.equals(type)) {
                if ("String".equalsIgnoreCase(map.get("datatype"))) {
                    if (WidgetCreator.getDrlValueMap().get("agendaGroup").getId().equals(id) ||
                            WidgetCreator.getDrlValueMap().get("ruleName").getId().equals(id)) {
                        drlrow = drlrow + map.get("value");
                    } else {
                        if (drlrow.lastIndexOf("startsWith") > -1 || drlrow.lastIndexOf("endsWith") > -1) {
                            drlrow = drlrow + "(\"" + map.get("value") + "\")";
                        } else
                            drlrow = drlrow + "\"" + map.get("value") + "\"";
                    }


                } else if ("Long".equalsIgnoreCase(map.get("datatype")) || "Double".equalsIgnoreCase(map.get("datatype")) || "Integer".equalsIgnoreCase(map.get("datatype")) || "Boolean".equalsIgnoreCase(map.get("datatype"))) {
                    drlrow = drlrow + map.get("value");

                } else if ("Date".equalsIgnoreCase(map.get("datatype"))) {
                    //drlrow = drlrow +"ruleHelper.getDate(\""+map.get("value")+"\")";
					if(map.get("value")!=null){
                    drlrow = drlrow + "\"" + map.get("value") + "\"";
					}else{
						drlrow = drlrow +"RFDate.getDate()";
					}
                } else if ("Map".equalsIgnoreCase(map.get("datatype")) || "List".equalsIgnoreCase(map.get("datatype"))) {
                    drlrow = drlrow + map.get("value");

                }
                //domain TODO 先把值直接输出，可以进一步调整把domain格式化到drl中增加可读型 加个map key=domainname.vname
            } else if (BaseBean.TYPE_DOMAIN.equals(type)) {
                DomainItem domainItem = BomCreator.getDomainItemById(id, this.drlDomain);
                if (domainItem!=null && "String".equalsIgnoreCase(domainItem.getType())) {
                    drlrow = drlrow + "\"" + map.get("value") + "\"";

                } else if (domainItem!=null && ("Double".equalsIgnoreCase(domainItem.getType()) || "Integer".equalsIgnoreCase(domainItem.getType()) || "Boolean".equalsIgnoreCase(domainItem.getType()))) {
                    drlrow = drlrow + map.get("value");

                } else {
                    drlrow = drlrow + "\"" + map.get("value") + "\"";
                }
                //函数
            } else if (BaseBean.TYPE_JFUN.equals(type)) {

            } else if (achoroperflag && BaseBean.TYPE_ANCHOR.equals(type)) {

                drlrow = drlrow + "@~@";
            } else if (achoroperflag && BaseBean.TYPE_SYMBOL.equals(type) && "semi".equals(map.get("name"))) {
                drlrow = drlrow + ";";
                
            }
            preMap = map;
        }
        if("if".equals(block)){//if语句
        	drlrow = BLOCK_MARK+"if(" +drlrow+" ){";
        }
        if("return".equals(block)){//return语句
        	drlrow = BLOCK_MARK+" return " +drlrow +";";
        }
        return drlrow;
    }
	/**
	 * 
	 * @param list 页面html内容 div解析成list
	 * @param achoroperflag true 用于变量定义
	 * @param leftOrRight 
	 * @param annotationList 为每一行代码所需添加的注释，可以用来存放额外信息，比如变量
	 * @return
	 * @throws Exception
	 */
	private String spanMap2Java(List<Map<String, String>> list, boolean achoroperflag,String leftOrRight,List<String> annotationList) throws Exception{
		String drlrow = "";
		String dataType = "";
        Map<String,?> preMap = null;
        
        //数据组 in or notin处理标识
        boolean flagCollConetent = false;
        //for,if语句处理标识
        String annotation = ""; //注释语句
        String block = null;
        String forIndex = null;//for语句索引变量
        String forEle = null;//循环子元素
        int index = 0;
        String paramInfo = "";
        
        //临时存储内容，逻辑分区处理，针对逻辑判断以及括号
        RuleParseList parseCache = new RuleParseList();
        //函数解析对象
        FuncParse funcParse = new FuncParse();
        //参数解析对象
        ParamParse paramParse = new ParamParse();
        for (Map<String, String> map : list) {
        	//System.out.println(""+index+" -- "+map);
            String type = map.get("type");
            String id = map.get("id");
            String name = map.get("name");
            //如果是函数变量，进行特殊处理，获取函数变量关联的方法进行替换
            String currisfuncparam = map.get("isfuncparam");
            if(list.size()>index+1) {
            	Map<String, String> nextMap = list.get(index+1);
            	String nextisfuncparam = nextMap.get("isfuncparam");
            	index++;
            	if("1".equals(nextisfuncparam)) {
            		paramInfo = name;
            		continue;
            	}
            }

            if("1".equals(currisfuncparam)) {
            	RuleDataparams ruledp = new RuleDataparams();
            	ruledp.setClassName(paramInfo);
            	ruledp.setName(name);
            	String key = paramInfo+"."+name;
            	if(!currentfuncParamMap.containsKey(key))currentfuncParamMap.put(key, ruledp);
                drlrow += funcParamMap.get(key);
        		continue;
        	}
            if (type == null || "".equals(type) || BaseBean.TYPE_OPER.equals(type)) {
                continue;
            }

            if (flagCollConetent) {
            	drlrow = drlrow + ", ";
            }
            //函数开始
            if (BaseBean.TYPE_JFUN.equals(type) && "left".equals(map.get("side"))) {
                JFun fun = JFunCreator.getJFunById(id);
                if (fun == null) {
                    fun = findJFunById(id);
                }
                //增加针对这个函数的解析存储对象,入栈
                funcParse = parseCache.pushFuncParse(fun);
                
                //缓存当前已解析的内容，切换为函数增长字符串
                parseCache.pushContents(drlrow);
                drlrow = "";
            //函数结束
            } else if (BaseBean.TYPE_JFUN.equals(type) && "right".equals(map.get("side"))) {
            	String newrow = parseCache.popContents();
                if(parseCache.getFuncSize()>1) {
                	drlrow = funcParse.toString();
                	funcParse = parseCache.popPrevFuncParse();//出栈，取出前一个，并删除当前
                }else {
                	parseCache.removeLastFunc();//删除最后一个
                	newrow += funcParse.toString();
                	String prevdrlrow = funcParse.getWaitLine();
                	if(StringUtils.isNotEmpty(prevdrlrow)) {
                		drlrow = prevdrlrow .replace(SymbolCreator.VAL_FLAG, newrow);
                    }else {
                    	drlrow = newrow;
                    }
                	funcParse = new FuncParse();
                }
                //参数锚点
            } else if (BaseBean.TYPE_ANCHOR.equals(type) && "anchor_funparam".equals(map.get("class"))) {
            	//函数参数
                funcParse.setCurrentParam(map.get("paramname"));
                //一个参数结束
            } else if ( funcParse.isFuncRuning() && BaseBean.TYPE_SYMBOL.equals(type) && "semi".equals(map.get("symtype"))) {
				if(StringUtils.isNotEmpty(dataType)&&isBaseType(dataType)){
					drlrow =  "("+dataType+")"+drlrow;
				}
    			funcParse.setRealParam(drlrow);
    			drlrow = "";
				dataType = "";
            } else if (BaseBean.TYPE_ANCHOR.equals(type) && ("for".equals(map.get("block"))||"if".equals(map.get("block"))||"return".equals(map.get("block")))) {
            	//for循环标记
                block = map.get("block");
                forIndex = map.get("forindex");
        		forEle = map.get("forele");
                
            } else if("end".equals(type)){
            	drlrow = BLOCK_MARK+"}";
            } else if("else".equals(type)){
            	drlrow = BLOCK_MARK+"}else{";
            }
            
            //站位显示
            //变量
            if (BaseBean.TYPE_TEMP.equals(type) || BaseBean.TYPE_SHOW.equals(type)) {
            	if("var".equals(map.get("block"))){
            		String var = map.get("value");
            		drlrow = BLOCK_MARK+var+" = null;\r\n"+TOP_MARK+var+"= new HashMap();";
            		return drlrow;
            	}
            	if( "true".equals(map.get("isinfor")) ) {
	        		if(drlrow.contains(SymbolCreator.VAL_FLAG)) {
	        			funcParse.setWaitLine(drlrow);
	        			drlrow = map.get("value");
	        		}else {
						paramParse.setDataSetName(map.get("value"));
						paramParse.setDataType("List");
						paramParse.setUsedType(ParamParse.USED_IN);
	    				paramParse.setSiteType(ParamParse.SITE_FOR);
						ParamParse typeObj = new ParamParse();
						typeObj.setDataSetName((String)map.get("datatype"));
						typeObj.setUsedType(ParamParse.USED_REF);
						typeObj.setSiteType(ParamParse.SITE_FOR);
						paramParse.setTypeObj(typeObj);
	        		}
        		}else {
                    drlrow = drlrow + map.get("value");
        		}
				dataType = map.get("datatype");
                //赋值符号
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && SymbolGuide.SYMTYP_LIST.equals(map.get("symtype"))) {
            	drlrow = drlrow + SymbolCreator.getSymbolById(id).getDrlSymbol();
                //锚点起始bom对象
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && SymbolGuide.SYMTYP_DECLARE.equals(map.get("symtype"))) {
                drlrow = drlrow + " : ";
                //锚点起始bom对象
            } else if (BaseBean.TYPE_SYMBOL.equals(type) && !SymbolGuide.SYMTYP_SEMICOLON.equals(map.get("symtype"))) {
            	Symbol symbol = SymbolCreator.getSymbolById(id);
            	if(symbol.getSymType().equals(SymbolGuide.SYMTYP_LOGIC) && !symbol.getName().equals("reverse")) {
            		//符号为and 或 or 意味着换行一个完整的条件结束
            		if( parseCache.isSetValueLine() ) {
            			//当该行为赋值语句时，直接拼接
            			drlrow = drlrow + symbol.getJavaSymbol();
            		}else {
                		if( parseCache.lastContentsContainsVAL_FLAG() ) {
                			drlrow = parseCache.lastContentsPopReplace(drlrow);
                		}
                		parseCache.addLogic(drlrow, symbol.getJavaSymbol());
                		drlrow = "";
            		}
            		
            	}else if(symbol.isChangeSite()) {
            		drlrow = symbol.getJavaSymbol().replace(SymbolCreator.PARAM_FLAG, drlrow);
                	parseCache.pushContents(drlrow);//已生成的内容存入栈
                    drlrow = "";
            	}else if("Date".equals(map.get("datatype"))) {
            		symbol = SymbolCreator.getSymbolById(id,SymbolGuide.SYMTYP_DATE);
            		drlrow = symbol.getJavaSymbol().replace(SymbolCreator.PARAM_FLAG, drlrow);
            		parseCache.pushContents(drlrow);//已生成的内容存入栈
            		drlrow = "";
            	}else if( parseCache.isSetValueLine() && " = ".equals(symbol.getJavaSymbol()) ) {
            		
            	}else {
            		drlrow = drlrow + symbol.getJavaSymbol();
            	}
                //list的添加
            } else if (BaseBean.TYPE_BOM.equals(type) && this.handlerBom.get(name) != null && BaseBean.TYPE_ANCHOR.equals(map.get("lefttype"))) {
            	//变量获取，获取前半部分，指数据模型的数据集
            	//获取类型
            	Map<String, String> curIndexMap = list.get(index);
    			if(StringUtils.isEmpty(curIndexMap.get("datatype"))) {
    				curIndexMap = list.get(index+1);
    			}
    			String datatype = curIndexMap.get("datatype");
    			if("list".equals(curIndexMap.get("grouptype"))) {
					if(isBaseType(datatype)) {
							datatype = "List";
					}else {
						datatype = "List<Map>";
					}
    			}
    			paramParse.setDataType(datatype);//类型
    			paramParse.setDataSetName(name);//参数
            	if("for".equals(block)){
        			paramParse.setUsedType(ParamParse.USED_IN);
        			paramParse.setSiteType(ParamParse.SITE_FOR);
            	}else if(leftOrRight.equals("left")){
            		//针对一般变量操作
        			paramParse.setUsedType(ParamParse.USED_IN);
        			paramParse.setSiteType(ParamParse.SITE_GENERAL);
				}else{
					//针对特殊位置的变量操作，如函数的参数，for循环参数 ，if参数
        			if(funcParse.isFuncRuning()) {
        				paramParse.setUsedType(ParamParse.USED_IN);
        				paramParse.setSiteType(ParamParse.SITE_FUNC);
        			}else {
        				paramParse.setUsedType(ParamParse.USED_IN);
        				paramParse.setSiteType(ParamParse.SITE_GENERAL);
        			}
					annotation = "//ruleHelper.setValue($insertMap,\""+name;
				}
            //bom对象或属性
            } else if (BaseBean.TYPE_BOM.equals(type)) {
            	if("for".equals(block)){
            		if("list".equals(map.get("grouptype"))){
            			drlrow =BLOCK_MARK//语句块标识
            					+ "	Map "+forEle+"=null;\r\n"
            					+ "	int "+forIndex+"=0;\r\n"+TOP_MARK
            					+ String.format("	for( %1$s=0;%1$s < ((List)ruleHelper.getValue($insertMap,\"%2$s\")).size();%1$s++){\r\n", forIndex,drlrow+"."+name)
            					+ String.format("		%1$s = (Map)((List)ruleHelper.getValue($insertMap,\"%2$s\")).get(%3$s);\r\n", forEle,drlrow+"."+name,forIndex);
            		}else if("Long".equals(map.get("datatype"))){
            			drlrow =BLOCK_MARK//语句块标识
            					+ "	int "+forIndex+"=0;\r\n"+TOP_MARK
            					+ String.format("	for( %1$s=0;%1$s < (Long)ruleHelper.getValue($insertMap,\"%2$s\");%1$s++){\r\n", forIndex,drlrow+"."+name);
            		}
            	}else if (preMap != null && BaseBean.TYPE_LISTTAIL.equals(preMap.get("type"))) {
            		if( ParamParse.USED_IN_LIST == paramParse.getUsedType()) {
            			ParamParse typeObj = paramParse.getTypeObj();
            			typeObj.setParamName(name);
            			typeObj.setDataType(map.get("datatype"));
            			paramParse.setKeyName(name);
            			drlrow = drlrow + paramParse.toString();
            			paramParse = new ParamParse();
            		}else {
            			drlrow = drlrow + ".get(\"" + name + "\")";
            		}
                } else {
                	//变量获取，后半部分
					paramParse.setParamName(name);
					if(!leftOrRight.equals("left")){
						if( "true".equals(preMap.get("isinfor")) ) {
 							//添加注释，用于增加引用参数
							ParamParse typeObj = paramParse.getTypeObj();
							typeObj.setDataType(map.get("datatype"));
							typeObj.setParamName(name);
 							annotation = "//ruleHelper.getValue($insertMap,\""+preMap.get("datatype")+"."+name+"\")\n";
 							if( !annotation.contains(annotation) )annotationList.add(annotation);
 							annotation = "";
						}else {
							annotation += "."+name+"\",0);\n";
							if( !annotation.contains(annotation) )annotationList.add(annotation);
							annotation = "";
						}
					}
					Map<String, String> indexMap = list.get(index);
					if( BaseBean.TYPE_LISTTAIL.equals(indexMap.get("type")) ) {
						//当前为list，下一个选择集合项
						paramParse.setUsedType(ParamParse.USED_IN_LIST);
						ParamParse typeObj = new ParamParse();
						typeObj.setDataSetName(map.get("datatype"));
						typeObj.setUsedType(ParamParse.USED_REF);
						paramParse.setTypeObj(typeObj);
					}else {
						//判断下一个为等号
						if ( "setValue".equals(indexMap.get("name")) && BaseBean.TYPE_SYMBOL.equals(indexMap.get("type")) && SymbolGuide.SYMTYP_SETVALUE.equals(indexMap.get("symtype")) ) {
							//参数为输出时，还需要输入值，变量解析才会结束 
							paramParse.setUsedType(ParamParse.USED_OUT);
							parseCache.setSetVParamParse(paramParse);
						}else if( "insert".equals(indexMap.get("name")) && "List".equals(paramParse.getDataType()) ) {
							drlrow = drlrow + paramParse.getDataSetName() + "."+paramParse.getParamName();
						}else {
							//参数为输入时，即使用ruleHelper.getValue(),进行取值，需要两个输入参数，已完备
							drlrow = drlrow + paramParse.toString();
						}
						paramParse = new ParamParse();
					}
				}
                //括号
            } else if (BaseBean.TYPE_GROUP.equals(type)) {
                if ("rightgroup".equals(map.get("handtype").toLowerCase())) {
                    if( parseCache.lastContentsContainsVAL_FLAG() ) {
                    	drlrow = parseCache.lastContentsPopReplace(drlrow);
                    }else if(parseCache.size()>0) {
                    		String row = parseCache.getLast(RuleParseList.KH);//获取最后一个值
                    		if(row.contains(SymbolCreator.VAL_FLAG)) {//如果包含，说明为枚举
                    			drlrow = row.replace(SymbolCreator.VAL_FLAG, drlrow);
                    			parseCache.removeLast(RuleParseList.KH);
                    		}else {
                    			String str = "";
                    			while(parseCache.getLastType()==RuleParseList.LOGIC) {
                    				str = parseCache.pullLast(RuleParseList.LOGIC)+parseCache.pullLast(RuleParseList.LOGIC_TYPE)+str;
                    			}
                    			drlrow = " ( " + str + drlrow + " ) ";
                    		}
                	}else {
                		drlrow = drlrow + " ) ";
                	}
                } else if ( parseCache.isSetValueLine() ) {
                	//当为赋值行时，括号不添加，直接拼接
                    drlrow = drlrow + " ( ";
                }else{
                	parseCache.add(drlrow,RuleParseList.KH);
                	drlrow = "";
                }
                if ("leftgroup".equals(map.get("handtype").toLowerCase()) && "coll".equals(map.get("widget"))) {
                    flagCollConetent = true;
                }
                if ("rightgroup".equals(map.get("handtype").toLowerCase()) && "coll".equals(map.get("widget"))) {
                    flagCollConetent = false;
                    //剔除多余的逗号
                    drlrow = drlrow.replaceAll("\\(\\s*,", "(").replaceAll(",\\s*,\\s*\\)", ")");
                }
                //list tail
            } else if (BaseBean.TYPE_LISTTAIL.equals(type)) {
                if ("size".equals(name)) {
                    drlrow = drlrow + ".size()";
                } else if ("item".equals(name)) {
                	if( ParamParse.USED_IN_LIST == paramParse.getUsedType()) {
                		paramParse.setIndexStr(map.get("index").trim());
                		if( ! BaseBean.TYPE_BOM.equals(list.get(index).get("type")) ) {
                			drlrow = drlrow + paramParse.toString();
                			paramParse = new ParamParse();
                		}
                	}else {
                		drlrow = drlrow + ".get(" + map.get("index").trim() + ") ";
                	}
                    
                }
                //值
            } else if (BaseBean.TYPE_VALUE.equals(type)) {
                if ("String".equalsIgnoreCase(map.get("datatype"))) {
                    if (WidgetCreator.getDrlValueMap().get("agendaGroup").getId().equals(id) || WidgetCreator.getDrlValueMap().get("ruleName").getId().equals(id)) {
                        drlrow = drlrow + map.get("value");
                    } else if (drlrow.lastIndexOf("startsWith") > -1 || drlrow.lastIndexOf("endsWith") > -1) {
                        drlrow = drlrow + "(\"" + map.get("value") + "\")";
                    } else {
                        drlrow = drlrow + "\"" + map.get("value") + "\"";
                    }
                } else if ("Long".equalsIgnoreCase(map.get("datatype")) || "Double".equalsIgnoreCase(map.get("datatype")) || "Integer".equalsIgnoreCase(map.get("datatype")) || "Boolean".equalsIgnoreCase(map.get("datatype"))) {
                    drlrow = drlrow + map.get("value");
                } else if ("Date".equalsIgnoreCase(map.get("datatype"))) {
                    //drlrow = drlrow +"ruleHelper.getDate(\""+map.get("value")+"\")";
					if(map.get("value")!=null){
						drlrow = drlrow + "\"" + map.get("value") + "\"";
					}else{
						drlrow = drlrow +"RFDate.getDate()";
					}
                } else if ("Map".equalsIgnoreCase(map.get("datatype")) || "List".equalsIgnoreCase(map.get("datatype"))) {
                    drlrow = drlrow + map.get("value");
                }
                //domain TODO 先把值直接输出，可以进一步调整把domain格式化到drl中增加可读型 加个map key=domainname.vname
            } else if (BaseBean.TYPE_DOMAIN.equals(type)) {
                DomainItem domainItem = BomCreator.getDomainItemById(id, this.drlDomain);
                if (domainItem!=null && "String".equalsIgnoreCase(domainItem.getType())) {
                    drlrow = drlrow + "\"" + map.get("value") + "\"";
                } else if (domainItem!=null && ("Double".equalsIgnoreCase(domainItem.getType()) || "Integer".equalsIgnoreCase(domainItem.getType()) || "Boolean".equalsIgnoreCase(domainItem.getType()))) {
                    drlrow = drlrow + map.get("value");
                } else {
                    drlrow = drlrow + "\"" + map.get("value") + "\"";
                }
                //函数
            } else if (BaseBean.TYPE_JFUN.equals(type)) {

            } else if (achoroperflag && BaseBean.TYPE_ANCHOR.equals(type)) {
                drlrow = drlrow + "@~@";
            } else if (achoroperflag && BaseBean.TYPE_SYMBOL.equals(type) && "semi".equals(map.get("name"))) {
                drlrow = drlrow + ";";
            }
            preMap = map;
        }
        
        if(parseCache.lastContentsContainsVAL_FLAG()) {
        	drlrow = parseCache.lastContentsPopReplace(drlrow);
        }
		while(parseCache.size()>0) {
			if(parseCache.getLastType()==RuleParseList.LOGIC) {
				drlrow = parseCache.pullLast(RuleParseList.LOGIC)+parseCache.pullLast(RuleParseList.LOGIC_TYPE)+drlrow;
			}else {
				drlrow = " ( "+ drlrow + parseCache.pullLast(RuleParseList.KH) + " ) ";
			}
		}
		//处理枚举
		drlrow = drlrow.replaceAll("Arrays.asList\\( \\(", "Arrays.asList\\(").replaceAll("\\) \\).contains\\(", "\\).contains\\(");
		
		//处理最后的setValue
		drlrow = parseCache.setFinalDrl(drlrow);
		
        if("if".equals(block)){//if语句
        	drlrow = BLOCK_MARK+"if(" +drlrow+" ){";
        }
        if("return".equals(block)){//return语句
        	drlrow = BLOCK_MARK+" return " +drlrow +";";
        }
        return drlrow;
    }

    private JFun findJFunById(String id) {
        for (JFun jfun : jfunList) {
            if (jfun.getId().equals(id)) return jfun;
        }
        throw new RuntimeException("未知函数：id=" + id);
    }

    /**
     * drl的mvel map取值 转换为java的方式 //this["PersonalInfo"]["validAsset"]["aaa"]["bbb"]
     * (String)ruleHelper.getValue($insertMap, "PersonalInfo.validAsset.aaa.bbb")
     * //this["PersonalInfo"]["validAsset"] (Map)ruleHelper.getValue($insertMap,
     * "PersonalInfo.validAsset")
     */
    private static String transformActionBomMethodType(String tempBom, Map<String, Bom> bomMapping) {
        String result = "";
        if (tempBom.trim().length() > 0) {
            if (tempBom.startsWith("this")) {
                result = result + "ruleHelper.getValue($insertMap,";
            }
            String tail = tempBom.substring(4);
            String bomNames = tail.replaceAll("\"]\\[\"", "\\.").replace("[\"", "").replace("\"]", "");
            result = result + bomNames + ")";
            BomField bomField = getBomField(bomNames, bomMapping);
            String type = !isBaseType(bomField.getDataType()) ? "Map" : bomField.getDataType();
            if (bomField.getGroupType().equalsIgnoreCase("List")) {
                type = "List";
            }
            return "(" + type + ")" + result;
        }
        return result;
    }

    private static BomField getBomField(String path, Map<String, Bom> bomMapping) {
        String[] bomNames = path.split("\\.");
        if (bomNames.length < 2) {
            return null;
        }
        Bom tempMClass = new Bom();
        for (int i = 0; i < bomNames.length; i++) {
            if (i == 0) {
                tempMClass = bomMapping.get(bomNames[i]);
            } else {

                BomField mField = new BomField();
                for (BomField bomField : tempMClass.getBomFields()) {
                    if (bomNames[i].equals(bomField.getName())) {
                        mField = bomField;
                    }
                }
                if (isBaseType(mField.getDataType()) || "list".equalsIgnoreCase(mField.getCollection()) || i == bomNames.length - 1) {
                    return mField;
                } else {
                    tempMClass = bomMapping.get(mField.getDataType());
                }
            }

        }
        return null;
    }

    /**
     * drl的mvel map取值 转换为java的方式 //this["PersonalInfo"]["validAsset"]["aaa"]["bbb"]
     * System.out.println( (String)(((Map)(((Map)(((Map)($insertMap.get("PersonalInfo"))).get("validAsset"))).get("aaa"))).get("bbb"))
     * ); //this["PersonalInfo"]["validAsset"] System.out.println( (Double)(((Map)($insertMap.get("PersonalInfo"))).get("validAsset"))
     * ); //this["PersonalInfo"]["validAsset"] System.out.println( (Map)($insertMap.get("PersonalInfo")
     * );
     */
    private static String transformActionBom(String tempBom, Map<String, Bom> bomMapping) {
        String result = "";
        if (tempBom.trim().length() > 0) {
            if (tempBom.startsWith("this")) {
                result = result + "$insertMap";
            }
            String tail = tempBom.substring(4);

            Pattern pattern = Pattern.compile("\\[\".*?\"\\]");
            Matcher matcher = pattern.matcher(tail);
            //String dataType= "";
            Bom bom = null;
            while (matcher.find()) {
                String bomName = matcher.group().replace("[\"", "").replace("\"]", "");
                if (bom == null) {
                    bom = bomMapping.get(bomName);

                    result = "((Map)" + result + ".get(\"" + bomName + "\"))";
                } else {
                    for (BomField bomField : bom.getBomFields()) {
                        if (bomField.getName().equals(bomName)) {
                            if (bomField.getCollection() != null && bomField.getCollection().toLowerCase().equals("list")) {
                                result = "((List)(" + result + ".get(\"" + bomName + "\")))";
                                break;

                            } else if (isBaseType(bomField.getDataType())) {
                                result = "(" + upCaseFirstWord(bomField.getDataType()) + ")" + result + ".get(\"" + bomName + "\")";
                                break;
                            } else {
                                result = "((Map)" + result + ".get(\"" + bomName + "\"))";
                                bom = bomMapping.get(bomField.getDataType());
                                break;
                            }
                        }
                    }
                    //bom =
                }
            }


        }
        return result;
    }

    private static boolean isBaseType(String dataType) {
        return "string_long_double_boolean_date_".indexOf(dataType.toLowerCase() + "_") >= 0;
    }

    private static String upCaseFirstWord(String str) {
        if ("Date".equals(str)) return "String";
        if (StringUtils.isNotBlank(str)) {
            return str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
        }
        return str;
    }
    public String funcActionHandler(List<Map<String, String>> list) throws Exception{
    	return funcActionHandler(list,false);
    }
    //action部分转换
    public String funcActionHandler(List<Map<String, String>> list,boolean typeChange) throws Exception {
		String drlaction = null;
		if(typeChange) {
			drlaction =  spanMap2Java(list, false,"right",new ArrayList<String>());
		}else {
			drlaction =  spanMap2Drl(list, false,"right");
		}
        String setStr = "";
        //赋值
        if (drlaction.indexOf("::=") >= 0) {
            String[] setValueStr = drlaction.split("::=");
            String left = setValueStr[0].replaceFirst("this", "").replaceAll("\"\\]\\[\"", ".").replaceAll("\\[\"", "").replaceAll("\"\\]", "").trim();
            //if()
            String right = setValueStr[1];
            String[] rightItem = right.split(" ");
            String rightResult = "";
            for (String string : rightItem) {
                if (string.matches("this\\[\".*\"\\]")) {
                    rightResult = rightResult + " " + transFuncActionBom(string, indexBom,typeChange);
                } else {
                    rightResult = rightResult + " " + string;
                }
            }
            rightResult = rightResult.replaceAll("&quot;", "\\\\\"");//将html转义符还原回去
            if(setValueStr[0].startsWith("this[")){//数据模型中的对象赋值
            	setStr = "ruleHelper.setValue(dataMap, \"" + left + "\", " + rightResult + ");";
            }else{//临时对象赋值
            	setStr = setValueStr[0]+" = "+rightResult +";";
            }
            //action.setContent(setStr);
            //插入
        } else if (drlaction.indexOf("@@=") >= 0) {

            String[] setValueStr = drlaction.split("@@=");
            String left = setValueStr[0].replaceFirst("this", "").replaceAll("\"\\]\\[\"", ".").replaceAll("\\[\"", "").replaceAll("\"\\]", "").trim();
            //if()
            String right = setValueStr[1];

            //this["rating_info"]["mylist22"]@@={name:"null",type:"sss",bigValue:111}
            if (drlaction.matches(".*\\{.*\\}.*")) { //插入对象
                String jsonstr = "\"" + right.replaceAll("\"", "\\\\\"") + "\"";
                jsonstr = jsonstr.replace("drools.getRule().getAgendaGroup()", "\"+drools.getRule().getAgendaGroup()+\"");
                jsonstr = jsonstr.replace("drools.getRule().getName()", "\"+drools.getRule().getName()+\"");

                setStr = "ruleHelper.insertObject(dataMap, \"" + left + "\", " + jsonstr + ");";
            } else {//插入值
                setStr = "ruleHelper.insertValue(dataMap, \"" + left + "\", " + right + ");";

            }
        } else if(drlaction.startsWith(BLOCK_MARK)){
        	setStr = drlaction.split(BLOCK_MARK)[1];
        	//判断是否包含需要置顶的语句(例：for语句中的临时变量需要在外面事先定义)
        	if(setStr.contains(TOP_MARK)){
        		String top = setStr.split(TOP_MARK)[0];
        		setStr = setStr.replace(TOP_MARK, "");
        	}
        }

        String reg = "this(\\[\"[a-zA-Z_0-9]*\"\\])+";
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(setStr);
        boolean finded = false;
        while (matcher.find()) {
            finded = true;
            String result = matcher.group();
            String conter = transFuncActionBom(result, indexBom,typeChange).replace("$", "\\$");
            matcher.appendReplacement(sb, conter);
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
    /**
     * drl的mvel map取值 转换为java的方式 //this["PersonalInfo"]["validAsset"]["aaa"]["bbb"]
     * System.out.println( (String)(((Map)(((Map)(((Map)($insertMap.get("PersonalInfo"))).get("validAsset"))).get("aaa"))).get("bbb"))
     * ); //this["PersonalInfo"]["validAsset"] System.out.println( (Double)(((Map)($insertMap.get("PersonalInfo"))).get("validAsset"))
     * ); //this["PersonalInfo"]["validAsset"] System.out.println( (Map)($insertMap.get("PersonalInfo")
     * );
     */
    private static String transFuncActionBom(String tempBom, Map<String, Bom> bomMapping,boolean typeChange) {
        String result = "";
        List<String> formatCodeInfo = new ArrayList<String>();
        if (tempBom.trim().length() > 0) {
            String tail = tempBom.substring(4);
            Pattern pattern = Pattern.compile("\\[\".*?\"\\]");
            Matcher matcher = pattern.matcher(tail);
            Bom bom = null;
            String bomName = null;
            String paramName = null;
            while (matcher.find()) {
                String tmpName = matcher.group().replace("[\"", "").replace("\"]", "");
                if (bom == null) {
                	bomName = tmpName;
                	bom = bomMapping.get(bomName);
                } else {
                	paramName=tmpName;
                }
            }
            formatCodeInfo.add(bomName+"."+paramName);
        }
        for(String bomNames : formatCodeInfo) {
        	String[] bomnameInfo = bomNames.split("\\.");
            Bom bom = bomMapping.get(bomnameInfo[0]);
            String paramNme = "";
            if(bomnameInfo.length==2) {
            	paramNme= bomnameInfo[1];
            }
            BomField tarBomField = null;
            for (BomField bomField : bom.getBomFields()) {
                if (bomField.getName().equals(paramNme)) {
                	tarBomField = bomField;
                	break;
                }
            }
            if(typeChange) {
            	String dataType = "";
            	if(tarBomField!=null) {
		            if (tarBomField.getCollection() != null && tarBomField.getCollection().toLowerCase().equals("list")) {
		            	dataType = "(List)";
		            } else if (isBaseType(tarBomField.getDataType())) {
		            	dataType =  "("+tarBomField.getDataType()+")";
		            }
            	}
            	result += dataType+"ruleHelper.getValue(dataMap,\""+bomnameInfo[0];
            }else {
            	result += "ruleHelper.getValue(dataMap,\""+bomnameInfo[0];
            }

            if (tarBomField!=null) {
                if (tarBomField.getCollection() != null && tarBomField.getCollection().toLowerCase().equals("list")) {
//                  result = "((List)(" + result + ".get(\"" + paramNme + "\")))";
//                  break;
                } else if (isBaseType(tarBomField.getDataType())) {
                    result =  "("+tarBomField.getDataType()+")"+result + "." + paramNme + "\")";
                    break;
                } else {
//                  result = "((Map)(" + result + ".get(\"" + paramNme + "\")))";
//                  bom = bomMapping.get(bomField.getDataType());
//                  break;
                }
            }
            
        }

        return result;
    }
    
    /**
     * 判断是否添加分号，并且添加
     * @param line
     * @return
     */
    public String addSemicolon(String lineStr) {
        String trimStr = lineStr.trim();
        if(trimStr.length() == 0 || trimStr.endsWith(";")||trimStr.endsWith("{")||trimStr.endsWith("}")) {
            
        } else {
        	lineStr = lineStr+";";
        }
        return lineStr;
    }
	public List<RuleDataparams> getContainFuncParams() {
		return new ArrayList<RuleDataparams>(currentfuncParamMap.values());
	}
    
}
